//
//  MKSearchViewController.m
//  ManKeCartoon
//
//  Created by dllo on 15/10/22.
//  Copyright © 2015年 ManKe. All rights reserved.
//

#import "MKSearchViewController.h"
#import "MKBaseHeader.h"
@interface MKSearchViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>


@property (nonatomic, assign) NSInteger number;

@end

@implementation MKSearchViewController

- (void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
    [_searchBar becomeFirstResponder];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self createBackButton];
    [self createSearchBar];
    [self createTableView];
    
    _number = 1;
    
}
- (void)createBackButton{
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(10, 24, 30, 30)];
    [self.navBarView addSubview:backButton];
    [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:@"iconfont-arrowleft.png"] forState:UIControlStateNormal];
  
}
- (void)createSearchBar{
    
    _searchBar = [[UITextField alloc]initWithFrame:CGRectMake(50, 24, SCREEN_WIDTH - 60, 30)];
    [self.navBarView addSubview:_searchBar];
    [_searchBar setBackgroundColor:[UIColor whiteColor]];
    [_searchBar setBorderStyle:UITextBorderStyleRoundedRect];
    _searchBar.placeholder = @"请输入关键字";
    _searchBar.delegate = self;
    
}
- (void)backClick{
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)createTableView{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];

    self.tableView.delegate =self;
    self.tableView.dataSource = self;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

        return self.resultArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        static NSString *resultCellID = @"resultCell";
        MKResultTableViewCell *resultCell = [tableView dequeueReusableCellWithIdentifier:resultCellID];
        if (resultCell == nil) {
            resultCell = [[MKResultTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:resultCellID];
        }
        MKSearchModel *model = _resultArray[indexPath.row];
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:model.title];
        
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:[model.title rangeOfString:_searchBar.text]];
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[model.title rangeOfString:_searchBar.text]];
        
        [resultCell getDateWithModel:model];
        [resultCell.titleNameLabel setAttributedText:attributedString];
        
        return resultCell;
        

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.resultArray.count != 0) {
        return SCREEN_HEIGHT/5;
    }
    return 0.00001;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    
    NSString *urlString = [[NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Search/comicSearchList/key_word/%@/page/1/listcnt/15/user_local_version/5.0.7/user_channel/2011", _searchBar.text] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    [AFNETWORK getDataWithNoCacheString:urlString block:^(id block) {
        _resultArray = [[NSMutableArray alloc] init];

        for (NSDictionary *dic in [block objectForKey:@"data"]) {
            MKSearchModel *model = [[MKSearchModel alloc] initWithDictionary:dic];
            [_resultArray addObject:model];

        }
        if (self.resultArray.count == 0) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"搜索提示" message:@"找遍都木有,已经哭晕!" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:alertAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        [_tableView reloadData];
        [self addFooter];
    }];
    [_searchBar resignFirstResponder];
    
    return YES;
}
- (void)addFooter{
    
    __block MKSearchViewController *vc = vc;
    [_tableView addLegendFooterWithRefreshingBlock:^{
        [vc loadMoreData];
    }];

    
}

- (void)loadMoreData{

    NSString *urlString = [[NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Search/comicSearchList/key_word/%@/page/%ld/listcnt/15/user_local_version/5.0.7/user_channel/2011", _searchBar.text, ++_number] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [AFNETWORK getDataWithNoCacheString:urlString block:^(id block) {
        
        for (NSDictionary *dic in [block objectForKey:@"data"]) {
            MKSearchModel *searchModel = [[MKSearchModel alloc] initWithDictionary:dic];
            NSInteger count = 0;
            for (MKSearchModel *model in self.resultArray) {
                
                if ([searchModel.title isEqualToString:model.title]) {
                    count++;
                }
            }
            if (count == 0) {
                [_resultArray addObject:searchModel];
            }
    
        }
        
        [_tableView reloadData];
        [_tableView.footer endRefreshing];

    }];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
        MKCartoonViewController *cartoonVc = [[MKCartoonViewController alloc] init];
        cartoonVc.comic_id = [_resultArray[indexPath.row] comic_id];
        
        [self.navigationController pushViewController:cartoonVc animated:NO];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    
    [_searchBar resignFirstResponder];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
